<template>
    <div class="group-initiate" :style="style">
        <div class="img-wrapper" v-show="imgDone"><img src="" alt="" class="resultImg"/></div>
        <div class="share-page" ref="share" v-show="!imgDone">
            <div class="share-header">
                <img :src="picBase64" alt="" class="product-img" @load="imgLoad"/>
                <div class="product-info">
                    <div class="product-name">{{ formatProductName}}</div>
                    <div class="product-price">{{ product.price }}元</div>
                </div>
            </div>
            <div class="share-main">
                <img :src="qrcodeWechat" style="width: 175px;height: 175px" v-if="interState"/>
                <qrcode :text="qrcode" :size="175" error-level="M" v-else/>
            </div>
            <div class="share-alert">
                <div class="share-user">{{nickname}}</div>
                <div class="share-text">的拼团</div>
            </div>
        </div>
        <div class="group-footer">长按图片保存至手机</div>
    </div>
</template>

<script>
    const HEIGHT = document.documentElement.clientHeight + 'px';
    import html2canvas from 'html2canvas';
    import {protocol} from '@/config';
    import {commonMixin, productMixin} from '@/common/mixin';
    import API from '@/request/api.js';
    import wx from 'weixin-js-sdk';
    import {isIOS} from '@/common/utils';

    export default {
        mixins: [productMixin, commonMixin],
        name: 'group-initiate',
        data() {
            return {
                style: {
                    height: HEIGHT
                },
                imgDone: false,
                showFlag: false,
                avatarBase64: '',
                picBase64: '',
                recordCount: 0,
                lastGid: '',
                product: {},
                groupid: '',
                qrcodeWechat: '',
                interState: false // 是否小程序环境,默认web环境
            };
        },
        computed: {
            uid() {
                return this.userInfo.uid ? this.userInfo.uid : '';
            },
            avatar() {
                return this.userInfo.avatar ? this.userInfo.avatar : '';
            },
            nickname() {
                if (!this.userInfo.nickname) {
                    return '';
                }
                return this.userInfo.nickname.length > 10 ? `${this.userInfo.nickname.substr(0, 10)}...` : this.userInfo.nickname;
            },
            qrcode() {
                const page = 'group-detail';
                let proto = protocol ? protocol : 'http';
                let system = !!this.$store.state.login.userInfo.system_id ? this.$store.state.login.userInfo.system_id : this.$store.state.login.system;
                let url = `${proto}://${document.domain}/welcome?&page=${page}&gid=${this.product.gid}&groupid=${this.groupid}&system=${system}&referid=${this.uid}`;
                return url;
            },
            formatProductName() {
                if (!this.product.name) {
                    return '';
                }
                return this.product.name.length > 15 ? `${this.product.name.substr(0, 15)}...` : this.product.name;
            },
            formatUserName() {
                if (!this.product.name) {
                    return '';
                }
                return this.product.name.length > 15 ? `${this.product.name.substr(0, 15)}...` : this.product.name;
            }
        },
        beforeRouteEnter(to, from, next) {
            // 修复iOS版微信h5 History兼容性问题
            if (isIOS() && to.path !== location.pathname) {
                location.assign(to.fullPath); // 此处不可使用location.replace
            } else {
                next();
            }
        },
        created() {
            this.showGlobaLoading();
            this.getCodeData();
        },
        mounted() {

            // this.prepareWxShare(this.qrcode, {
            //     name: '我的拼团',
            //     dec: '',
            //     pic: this.picBase64,
            // });
        },
        methods: {
            imgLoad() {
                console.log('loaded#############');
                this.hideGlobaLoading(); //关闭loading

            },
            // download(){
            //     this.$nextTick(()=>{
            //         this.domToImg()
            //     })
            // },
            getCodeData() {
                this.request.get(API.groupShareCode, {
                    pid: this.$route.query.pid,
                }).then((res) => {
                    if (res.status) {
                        this.product = res.info;
                        this.groupid = res.groupid;
                        if (window.__wxjs_environment === 'miniprogram') {
                            //    判断是否先程序环境
                            console.log('我是小程序段啊啊啊啊啊啊啊啊啊啊');
                            this.interState = true;
                            this.request.post(API.qrcode, {
                                scene: {
                                    page: 'group-detail',
                                    gid: this.product.gid,
                                    groupid: this.groupid,
                                    system: this.userInfo.system_id,
                                    referid: this.uid
                                }

                            }).then(res => {
                                console.log(res, 'ressss');
                                this.qrcodeWechat = res.base64;
                                this.show();
                            });
                            wx.miniProgram.postMessage({
                                data: {
                                    page: 'group-detail',
                                    gid: this.product.gid,
                                    groupid: this.groupid,
                                    system: this.userInfo.system_id,
                                    referid: this.uid,
                                    type: 'group-detail'
                                }
                            });
                        } else {
                            this.show();
                        }
                    } else {
                        this.$toast({
                            message: res.msg,
                            duration: 1000
                        });
                        this.$router.go(-1);
                    }

                }).catch((err) => {
                    this.hideGlobaLoading(); //关闭loading
                    console.error('groupShareCode-err', err);
                });

            },
            async show() {
                if (this.lastGid == this.product.gid) {
                    this.showFlag = true;
                    return;
                }
                this.imgDone = false;
                console.log('start show share');
                // 非精选记录分享记录
                // if (this.product.gid && this.type != 'refine' && this.recordCount === 0) {
                //     this._recordShare();
                // }
                if (this.product.name) {
                    //获取base64编码 解决移动端跨域问题
                    try {
                        // 写法一
                        let [productResult] = await Promise.all([this._getBase64(this.product.pic)]);
                        // let [avatarResult, productResult] = await Promise.all([this._getBase64(this.avatar), this._getBase64(this.product.pic)]);
                        // this.avatarBase64 = this.formatBase64Src(avatarResult.content);
                        this.picBase64 = this.formatBase64Src(productResult.content);
                    } catch (e) {
                        console.log(e);
                    }

                    // this.showFlag = true;
                    this.$nextTick(() => {
                        this.domToImg();
                    }, 20);
                    this.lastGid = this.product.gid;
                }
            },
            hide() {
                this.showFlag = false;
            },
            _getBase64(url) {
                if (!url) {
                    return '';
                }
                return this.request.get(API.picbase64, {url: url});
            },
            _recordShare() {
                return this.request
                    .post(API.shareAdd, {
                        source: this.type === 'online' ? 1 : 2,
                        gid: this.product.gid,
                        from: this.type === 'online' ? 1024 : this.sid
                    })
                    .then((res) => {
                        if (res) {
                            this.recordCount++;
                        }
                    })
                    .catch((e) => {
                        console.log(e);
                    });
            },
            formatBase64Src(base64) {
                return `data:image/png;base64,${base64}`;
            },
            domToImg() {
                let shareNode = this.$refs.share;
                const opts = {
                    scrollY: 0, // 纵向偏移量 写死0 可以避免滚动造成偶尔偏移的现象
                    useCORS: true // 【重要】开启跨域配置
                };
                setTimeout(() => {
                    html2canvas(shareNode, opts).then(_canvas => {
                        const img = document.querySelector('.resultImg');
                        img.src = _canvas.toDataURL();
                        this.imgDone = true;
                    });
                }, 20);
            },
            // domToImg() {
            //     let shareNode = document.querySelector('.share-page');
            //     console.log(shareNode.offsetWidth, shareNode.offsetHeight);
            //     var width = shareNode.offsetWidth; //获取dom 宽度
            //     var height = shareNode.offsetHeight; //获取dom 高度
            //     var canvas = document.createElement('canvas'); //创建一个canvas节点
            //     var scale = window.devicePixelRatio || 5; //定义任意放大倍数 支持小数
            //     canvas.width = width * scale; //定义canvas 宽度 * 缩放
            //     canvas.height = height * scale; //定义canvas高度 *缩放
            //     canvas.style.width = width + 'px';
            //     canvas.style.height = height + 'px';
            //     canvas.getContext('2d').scale(scale, scale);
            //     canvas.getContext('2d').translate(0, 0);
            //     var opts = {
            //         scale: scale, // 添加的scale 参数
            //         canvas: canvas, //自定义 canvas
            //         logging: true, //日志开关，便于查看html2canvas的内部执行流程
            //         width: width, //dom 原始宽度
            //         height: height,
            //         dpi: window.devicePixelRatio,
            //         useCORS: true, // 【重要】开启跨域配置
            //         windowWidth: shareNode.scrollWidth,
            //         windowHeight: shareNode.scrollHeight
            //     };
            //
            //     html2canvas(shareNode, opts).then((canvas) => {
            //         var ctx = canvas.getContext('2d');
            //         // 【重要】关闭抗锯齿
            //         ctx.mozImageSmoothingEnabled = false;
            //         ctx.webkitImageSmoothingEnabled = false;
            //         ctx.msImageSmoothingEnabled = false;
            //         ctx.imageSmoothingEnabled = false;
            //
            //         let img = document.querySelector('.resultImg');
            //         img.src = canvas.toDataURL();
            //         console.log(canvas.toDataURL().substr(10, 20));
            //         this.imgDone = true;
            //         // this.downloadFile(`${this.nickname}的拼团.png`, canvas.toDataURL());
            //     });
            // },
            // download(){
            //     this.downloadFile(`分享${this.product.name}.png`, canvas.toDataURL());
            // },
            downloadFile(fileName, content) {
                console.log('downloadFile begin');
                const aLink = document.createElement('a');
                const blob = this.base64ToBlob(content); // new Blob([content]);

                const evt = document.createEvent('HTMLEvents');
                evt.initEvent('click', true, true); // initEvent 不加后两个参数在FF下会报错  事件类型，是否冒泡，是否阻止浏览器的默认行为
                aLink.download = fileName;
                aLink.href = URL.createObjectURL(blob);
                aLink.click();
            },
            base64ToBlob(code) {
                var arr = code.split(','),
                    mime = arr[0].match(/:(.*?);/)[1],
                    bstr = atob(arr[1]),
                    n = bstr.length,
                    u8arr = new Uint8Array(n);
                while (n--) {
                    u8arr[n] = bstr.charCodeAt(n);
                }
                return new Blob([u8arr], {type: mime});
            }
        }
    };
</script>

<style scoped lang="stylus" rel="stylesheet/stylus">
    @import '~assets/main.styl'
    .group-initiate {
        width 100%
        overflow-x hidden
        background main-liner 100% 100% no-repeat
        display flex
        flex-direction column
        align-items center
    }

    * {
        box-sizing border-box
    }

    .img-wrapper {
        /*background #f9f9f9*/
        width 296px
        height 425px
        margin: 0 auto;
        margin-top 20%
        border-radius main-radius

        .resultImg {
            /*width 100%*/
            /*height 100%*/
            width 296px
            border-radius main-radius
        }

    }

    .share-page {
        background #f9f9f9
        width 296px
        height 425px
        margin: 0 auto;
        margin-top 20%
        /*margin-left: 25px;*/
        /*padding-left 45px*/
        border-radius main-radius

        .share-header {
            width 100%
            height 100px
            margin 0 auto
            text-align left
            font-size word14
            color gray6
            padding-top 32px
            padding-left 25px
            display flex
            flex-direction row

            img {
                vertical-align middle
                width 68px
                height 68px
                margin-right smallMargin
            }

            .product-info {
                word-vw(gray3, word14)
                line-height 19px
                display flex
                flex-direction column
                justify-content space-between

                .product-name {
                    /* overflow:hidden;
                     text-overflow:ellipsis;
                     display:-webkit-box;
                     -webkit-box-orient:vertical;
                     -webkit-line-clamp:2;*/
                }

                .product-price {
                    margin-top titleMargin
                }
            }
        }

        .share-main {
            width 175px
            height 175px
            margin 50px auto auto auto

            .product-img {
                width 175px
                height 175px
            }
        }

        .share-alert {
            margin 10px auto
            text-align center
            font-size word14
            line-height 19px
            color gray3
            width vw(175)
            height 4em

            .share-user {
                /* overflow:hidden;
                 text-overflow:ellipsis;
                 display:-webkit-box;
                 -webkit-box-orient:vertical;
                 -webkit-line-clamp:3;*/
            }

            .share-text {
                margin-top titleMargin
            }
        }
    }

    .group-footer {
        /*border grayF 1px solid*/
        width vw(175)
        height vw(25)
        border-radius all-radius
        color grayF
        margin-top 20px
        display flex
        align-items center
        justify-content center
        text-align center
        font-size word14
        line-height 19px
    }

</style>
